#include <iostream>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <string>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

using namespace std;

void Usage(const string& proc)
{
    std::cout << proc << " serverip serverport\n" << endl;
}

// ./udpclient serverip serverport
int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    int clientfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (clientfd < 0)
    {
        cout << "create socket fail\n" << endl;
        exit(1);
    }
    cout << "create socket success : " << clientfd << endl;


    struct sockaddr_in ServerSocket;
    memset(&ServerSocket,0,sizeof(ServerSocket));
    socklen_t Slen = sizeof(ServerSocket);
    ServerSocket.sin_family = AF_INET;
    ServerSocket.sin_addr.s_addr = inet_addr(argv[1]);
    ServerSocket.sin_port = htons(stoi(argv[2]));

    while (1)
    {
        string inbuffer;
        cout << "Please Enter# ";
        getline(cin,inbuffer);

        int n = sendto(clientfd, inbuffer.c_str(), inbuffer.size(), 0, (struct sockaddr*)&ServerSocket, Slen);
        if (n < 0)
        {
            cout << "sendto fail , errno : " << errno <<  ", error : " << strerror(errno) << endl;
            break;
        }
        else
        {
            cout << inbuffer << endl;

            struct sockaddr_in temp;
            socklen_t tlen = sizeof(temp);
            char buffer[1024];
            int m = recvfrom(clientfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&temp, &tlen);
            if(m > 0)
            {
                buffer[m] = 0;
                cout << "Server say#" << buffer << endl;
            }
            else
            {
                break;
            }
        }
    }

    close(clientfd);

    return 0;
}


